const Core = require('@alicloud/pop-core');
const dayjs = require('dayjs')

let client = new Core({
    accessKeyId: 'LTAI5tPYxScekCEYhRSjLbgY',
    accessKeySecret: 'hbsCOkuVXij7EkzJgAU7tCKNXFkDzO',
    // securityToken: '<your-sts-token>', // use STS Token
    endpoint: 'https://dysmsapi.aliyuncs.com',
    apiVersion: '2017-05-25'
});

//验证码初始值
let codes = ''

const requestOption = {
    method: 'POST',
    formatParams: false,

};

class SmCode {
    constructor(ctx, iphone, codeData) {
        this.ctx = ctx;
        this.iphone = iphone;
        this.codeData = codeData;
    }

    async codeFun() {
        //随机生成6位数短信验证码: 如果验证码是以0开头的，那么用户出现的验证码不会出现0
        codes = Math.random().toString().slice(-6);

        const params = {
            "SignName": "小杨外卖",
            "PhoneNumbers": this.iphone,
            "TemplateCode": "SMS_276392362",
            "TemplateParam": `{code:${codes}}`
        }
        let ctx = this.ctx;
        try {
            const res = await client.request('SendSms', params, requestOption);
            if (res.Message === 'OK' && res.Code === 'OK') {
                ctx.body = {
                    msg: '验证码发送成功',
                    code: 0
                };
                ctx.status = 200;
            } else {
                ctx.body = {
                    msg: '验证码发送失败',
                    code: 1
                };
                ctx.status = 202;
            }
        } catch (err) {
            if (err.code === 'isv.BUSINESS_LIMIT_CONTROL') {
                ctx.body = {
                    msg: '验证码发送太频繁，请稍后再试',
                    code: 1
                };
                ctx.status = 202;
            } else {
                ctx.body = {
                    msg: '验证码发送失败',
                    code: 1
                };
                ctx.status = 202;
            }
        }
    }

    //验证验证码是否正确
    async verificationCode() {

        let ctx = this.ctx;

        let params = {
            "PhoneNumber": this.iphone,
            "SendDate": dayjs(new Date()).format('YYYYMMDD'),
            "CurrentPage": 1,
            "PageSize": 1
        }

        let requestOption = {
            method: 'POST',
            formatParams: false,

        };
        try {
            let query = await client.request('QuerySendDetails', params, requestOption)
            let {SmsSendDetailDTOs: {SmsSendDetailDTO}, Code, Message, TotalCount} = query;
            // console.log(SmsSendDetailDTO, query);
            if (Message === 'OK' && Code === 'OK') {
                if (TotalCount === 0) {
                    throw('验证码不正确')
                }
                if (SmsSendDetailDTO[0].SendDate === 2) {
                    throw('验证码发送失败,请重试')
                }
                //比较已经发送的验证码和用户输入的验证码是否一致
                if (this.codeData !== codes) {
                    throw('验证码填写错误')
                }
            }
        } catch (err) {
            ctx.body = {
                msg: err,
                code: 1
            };
            ctx.status = 202;
        }
    }
}

module.exports = {
    SmCode
}
